<template>
	<view class="container">
		<!-- 公告列表 -->
		<scroll-view 
			class="announcement-list" 
			scroll-y 
		>
			<!-- 置顶公告 -->
			<view 
				class="announcement-item pinned"
				v-for="item in pinnedAnnouncements" 
				:key="item.id"
				@tap="goToDetail(item)"
			>
				<view class="item-header">
					<view class="left">
						<text class="pin-tag">置顶</text>
						<text class="title">{{ item.title }}</text>
					</view>
					<text class="time">{{ formatTime(item.create_time) }}</text>
				</view>
				<view class="content-wrapper">
					<text 
						class="content" 
						:class="{ 'collapsed': !expandedIds.includes(item.id) }"
					>{{ item.content }}</text>
					<view 
						class="expand-btn"
						v-if="needExpand(item.content)"
						@tap.stop="toggleExpand(item.id)"
					>
						<text>{{ expandedIds.includes(item.id) ? '收起' : '展开' }}</text>
						<uni-icons 
							:type="expandedIds.includes(item.id) ? 'top' : 'bottom'" 
							size="12" 
							color="#666"
						></uni-icons>
					</view>
				</view>
				<view class="item-footer">
					<text class="publisher">发布者: {{ item.username }}</text>
				</view>
			</view>
			
			<!-- 普通公告 -->
			<view 
				class="announcement-item"
				v-for="item in normalAnnouncements" 
				:key="item.id"
				@tap="goToDetail(item)"
			>
				<view class="item-header">
					<text class="title">{{ item.title }}</text>
					<text class="time">{{ formatTime(item.create_time) }}</text>
				</view>
				<view class="content-wrapper">
					<text 
						class="content" 
						:class="{ 'collapsed': !expandedIds.includes(item.id) }"
					>{{ item.content }}</text>
					<view 
						class="expand-btn"
						v-if="needExpand(item.content)"
						@tap.stop="toggleExpand(item.id)"
					>
						<text>{{ expandedIds.includes(item.id) ? '收起' : '展开' }}</text>
						<uni-icons 
							:type="expandedIds.includes(item.id) ? 'top' : 'bottom'" 
							size="12" 
							color="#666"
						></uni-icons>
					</view>
				</view>
				<view class="item-footer">
					<text class="publisher">发布者: {{ item.username }}</text>
				</view>
			</view>
		</scroll-view>
		
		<!-- 无数据提示 -->
		<view class="empty-tip" v-if="announcements.length === 0 && !loading">
			<text>暂无系统公告</text>
		</view>
		
		<!-- 公告详情弹层 -->
		<view class="detail-popup" v-if="showDetail">
			<view class="mask" @tap="closeDetail"></view>
			<view class="popup-content">
				<view class="popup-header">
					<view class="left">
						<view class="back-btn" @tap="closeDetail">
							<uni-icons type="left" size="18" color="#333"></uni-icons>
						</view>
					</view>
					<text class="title">{{ detailData.title }}</text>
				</view>
				<scroll-view class="popup-body" scroll-y>
					<!-- 发布者信息 -->
					<view class="publisher-info">
						<image class="avatar" src="/static/min_logo.png" mode="aspectFill"></image>
						<view class="info-right">
							<text class="name">小碎信息</text>
							<text class="time">{{ formatTime(detailData.create_time) }}</text>
						</view>
					</view>

					<!-- 公告内容 -->
					<view class="detail-content">
						<text class="content-text">{{ detailData.content }}</text>
					</view>
					
					<!-- 只保留图片展示 -->
					<view class="media-list" v-if="detailData.media_data?.length > 0">
						<!-- 单张图片时全宽显示 -->
						<image 
							v-if="imageMedias.length === 1"
							:key="imageMedias[0].id"
							:src="handleImageUrl(imageMedias[0].media_url)"
							mode="widthFix"
							class="media-image"
							@tap="previewImage(imageMedias[0].media_url)"
						></image>
						
						<!-- 多张图片时使用九宫格布局 -->
						<view class="image-grid" v-else>
							<view 
								class="grid-item"
								v-for="media in imageMedias" 
								:key="media.id"
								@tap="previewImage(media.media_url)"
							>
								<image 
									:src="handleImageUrl(media.media_url)"
									mode="aspectFill"
									:class="[
										'grid-image',
										imageMedias.length === 4 ? 'four-grid' : ''
									]"
								></image>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { api } from '@/utils/request'

// 公告列表
const announcements = ref([])
// 展开的公告ID列表
const expandedIds = ref([])

// 加载状态
const loading = ref(false)

// 详情相关
const showDetail = ref(false)
const detailData = ref({})

// 只保留图片媒体
const imageMedias = computed(() => {
	return detailData.value.media_data?.filter(media => media.media_type === '图片') || []
})

// 分离置顶和普通公告
const pinnedAnnouncements = computed(() => {
	return announcements.value.filter(item => item.is_pinned)
})

const normalAnnouncements = computed(() => {
	return announcements.value.filter(item => !item.is_pinned)
})

// 获取公告列表
const getAnnouncements = async () => {
	if(loading.value) return
	
	try {
		loading.value = true
		const res = await api.request({
			url: '/api/system/get_system_announcement/',
			method: 'GET',
			data: {
				page: 1,
				page_size: 999 // 获取所有公告
			}
		})
		
		if(res.code === 200) {
			announcements.value = res.data.results
		}
	} catch(err) {
		console.error('获取公告失败', err)
		uni.showToast({
			title: '获取公告失败',
			icon: 'none'
		})
	} finally {
		loading.value = false
	}
}

// 格式化时间
const formatTime = (time) => {
	if(!time) return ''
	const date = new Date(time)
	return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}

// 判断是否需要展开按钮
const needExpand = (content) => {
	return content && content.length > 100
}

// 切换展开状态
const toggleExpand = (id) => {
	const index = expandedIds.value.indexOf(id)
	if(index > -1) {
		expandedIds.value.splice(index, 1)
	} else {
		expandedIds.value.push(id)
	}
}

// 获取详情
const goToDetail = async (item) => {
	try {
		const res = await api.request({
			url: '/api/system/get_system_announcement_detail/',
			method: 'GET',
			data: {
				system_announcement_id: item.id
			}
		})
		
		if(res.code === 200) {
			detailData.value = res.data
			showDetail.value = true
		}
	} catch(err) {
		console.error('获取公告详情失败', err)
		uni.showToast({
			title: '获取详情失败',
			icon: 'none'
		})
	}
}

// 关闭详情
const closeDetail = () => {
	showDetail.value = false
	detailData.value = {}
}

// 处理图片URL
const handleImageUrl = (url) => {
    
	if(!url) return ''

	// 如果已经包含http或https,则直接返回
	if(url.startsWith('http://') || url.startsWith('https://')) {
		return url
	}
	// 否则拼接BASE_URL
    
	return api.BASE_URL + url
}

// 预览图片
const previewImage = (url) => {
	const imageUrls = imageMedias.value.map(media => handleImageUrl(media.media_url))
	uni.previewImage({
		urls: imageUrls,
		current: handleImageUrl(url)
	})
}

onMounted(() => {
	getAnnouncements()
})
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	background: #f5f5f5;
	padding: 20rpx;
}

.announcement-list {
	height: calc(100vh - 40rpx);
}

.announcement-item {
	background: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
	
	&.pinned {
		border-left: 6rpx solid #ff6b6b;
	}
	
	.item-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
		
		.left {
			display: flex;
			align-items: center;
			gap: 12rpx;
			
			.pin-tag {
				background: #ff6b6b;
				color: #fff;
				font-size: 24rpx;
				padding: 4rpx 12rpx;
				border-radius: 6rpx;
			}
		}
		
		.title {
			font-size: 32rpx;
			color: #333;
			font-weight: bold;
		}
		
		.time {
			font-size: 24rpx;
			color: #999;
		}
	}
	
	.content-wrapper {
		.content {
			font-size: 28rpx;
			color: #666;
			line-height: 1.6;
			
			&.collapsed {
				display: -webkit-box;
				-webkit-box-orient: vertical;
				-webkit-line-clamp: 3;
				overflow: hidden;
			}
		}
		
		.expand-btn {
			display: flex;
			align-items: center;
			justify-content: center;
			gap: 4rpx;
			margin-top: 20rpx;
			
			text {
				font-size: 24rpx;
				color: #666;
			}
		}
	}
	
	.item-footer {
		margin-top: 20rpx;
		padding-top: 20rpx;
		border-top: 1rpx solid #eee;
		
		.publisher {
			font-size: 24rpx;
			color: #999;
		}
	}
	
	&:active {
		opacity: 0.8;
	}
}

.empty-tip {
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	text-align: center;
	font-size: 28rpx;
	color: #999;
}

/* 修改详情弹层样式 */
.detail-popup {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	z-index: 999;
	display: flex;
	align-items: center;
	justify-content: center;
	
	.mask {
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
	}
	
	.popup-content {
		position: relative;
		width: 90%;
		max-width: 750rpx;
		height: 80vh;  // 限制最大高度
		background: #fff;
		border-radius: 24rpx;
		overflow: hidden;
		display: flex;  // 使用flex布局
		flex-direction: column;  // 垂直排列
		
		.popup-header {
			padding: 0 30rpx;
			height: 88rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			border-bottom: 1rpx solid #eee;
			background: #f8f8f8;
			flex-shrink: 0;  // 不允许压缩
			
			.left {
				display: flex;
				align-items: center;
				gap: 20rpx;

				.back-btn {
					padding: 10rpx;
					margin-left: -10rpx;

					&:active {
						opacity: 0.7;
					}
				}

				.title {
					font-size: 32rpx;
					color: #333;
					font-weight: 500;
					// 标题过长时显示省略号
					max-width: 400rpx;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}
			}
		}
		
		.popup-body {
			flex: 1;  // 占满剩余空间
			overflow-y: auto;  // 内容过多时可滚动
			-webkit-overflow-scrolling: touch;  // 优化iOS滚动
			padding: 0;
			box-sizing: border-box;
			background: #f5f5f5;

			.publisher-info {
				padding: 30rpx;
				display: flex;
				align-items: center;
				gap: 20rpx;
				background: #fff;
				flex-shrink: 0;  // 不允许压缩

				.avatar {
					width: 80rpx;
					height: 80rpx;
					border-radius: 8rpx;
					flex-shrink: 0;  // 不允许压缩
				}

				.info-right {
					display: flex;
					flex-direction: column;
					gap: 8rpx;
					flex: 1;  // 占满剩余空间
					min-width: 0;  // 解决文本溢出问题

					.name {
						font-size: 28rpx;
						color: #333;
						font-weight: 500;
						// 名称过长时显示省略号
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
					}

					.time {
						font-size: 24rpx;
						color: #999;
					}
				}
			}
			
			.detail-content {
				margin: 20rpx;
				padding: 30rpx;
				background: #fff;
				border-radius: 8rpx;
				box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);

				.content-text {
					font-size: 28rpx;
					color: #333;
					line-height: 1.6;
					word-break: break-all;  // 允许在任意字符间断行
					white-space: pre-wrap;  // 保留换行符和空格
					overflow-wrap: break-word;  // 长单词换行
				}
			}
			
			.media-list {
				margin: 20rpx;
				padding: 20rpx;
				background: #fff;
				border-radius: 8rpx;
				box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.04);
				
				/* 单张图片样式 */
				.media-image {
					width: 100%;  // 修改为100%宽度
					max-width: 600rpx;  // 限制最大宽度
					height: auto;  // 高度自适应
					max-height: 600rpx;  // 限制最大高度
					border-radius: 12rpx;
					object-fit: contain;
					margin: 0 auto;  // 居中显示
					display: block;
				}
				
				/* 九宫格样式 */
				.image-grid {
					display: grid;
					grid-gap: 4rpx;
					width: 606rpx; // 3张图片的总宽度(200*3 + 3*2)
					
					/* 2张图片 */
					&:has(.grid-item:nth-child(2):last-child) {
						grid-template-columns: repeat(2, 1fr);
						
						.grid-item {
							height: 200rpx;
							width: 200rpx;
						}
					}
					
					/* 3张图片 */
					&:has(.grid-item:nth-child(3):last-child) {
						grid-template-columns: repeat(3, 1fr);
						
						.grid-item {
							height: 200rpx;
							width: 200rpx;
						}
					}
					
					/* 4张图片 */
					&:has(.grid-item:nth-child(4):last-child) {
						grid-template-columns: repeat(3, 1fr);
						
						.grid-item {
							height: 200rpx;
							width: 200rpx;
						}
					}
					
					/* 5-9张图片 */
					&:has(.grid-item:nth-child(5)) {
						grid-template-columns: repeat(3, 1fr);
						
						.grid-item {
							height: 200rpx;
							width: 200rpx;
						}
					}
					
					.grid-item {
						position: relative;
						display: inline-block;
						border-radius: 8rpx;
						overflow: hidden;
						background: #f5f5f5;
						
						&:active {
							opacity: 0.8;
						}
						
						.grid-image {
							width: 100%;
							height: 100%;
							object-fit: cover;
						}
					}
				}
			}
		}
	}
}
</style>
